<%--
  角色维护界面
  User: wangyang
  Date: 12-10-9
  Time: 下午1:30
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/common/tag/taglibs.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>角色列表</title>
    <link rel="stylesheet" type="text/css" href="<c:url value='/js/easyUI/themes/default/easyui.css' />"/>
    <link rel="stylesheet" type="text/css" href="<c:url value='/js/easyUI/themes/icon.css' />"/>
    <script type="text/javascript" src="<c:url value='/js/jquery.min.js' />"></script>
    <script type="text/javascript" src="<c:url value='/js/easyUI/jquery.easyui.min.js' />"></script>
    <script type="text/javascript" src="<c:url value='/js/easyUI/locale/easyui-lang-zh_CN.js' />"></script>
    <link rel="stylesheet" type="text/css" href="<c:url value='/css/query_list.css' />"/>
    <script type="text/javascript" src="<c:url value='/js/validatebox.js' />"></script>
    <script type="text/javascript" src="<c:url value='/js/message.js' />"></script>
    <style type="text/css">
        .columnTitle {
            font-weight:bold;
        }
    </style>
    <script type="text/javascript">
        // 上一次的行标识
        var lastIndex;
        // 部门集合
        var depts = new Array();
        // 页面加载初始化方法
        $(function () {
            $.ajax({
                type: "post",
                url: "<c:url value='/system/queryComboboxByDept.do'/>",
                dataType:'json',
                success: function (data) {
                    for(var i=0; i<data.length; i++){
                        var dept = new Array();
                        dept[0] = data[i].id;
                        dept[1] = data[i].text;
                        depts[i] = dept;
                    }
                }
            });

            initDataGrid();
        });
        // 数据表格初始化方法
        function initDataGrid() {
            $('#displayTable').datagrid({
                fit:true, //表格自适应
                fitColumns:true, //列自适应
                nowrap:true, //是否换行
                autoRowHeight:false, //自动行高
                striped:true,
                collapsible:true, //是否可折叠
                url:'<c:url value="/system/queryRoles.do" />',
                sortName:'orderId',
                sortOrder:'asc',
                remoteSort:false,
                idField:'roleId',
                singleSelect:false, //是否单选
                pagination:true, //分页控件
                rownumbers:true, //行号
                scrollbarSize:0,
                loadMsg:"数据加载中.....",
                rowStyler:function (index, row) {
                    if (row.deltag == 1) {
                        return 'color:#748494;';
                    }
                },
                frozenColumns:[
                    [
                        {field:'ck', checkbox:true},
                        {field:'roleId', hidden:true}
                    ]
                ],
                columns:[
                    [
                        {field:'roleName', title:'<span class="columnTitle">角色名称</span>', width:100, editor:'text'},
                        {field:'deptId', title:'<span class="columnTitle">部门</span>', width:100, formatter:deptFormatter,
                            editor:{
                                type:'combobox',
                                options:{
                                    valueField:'id',
                                    textField:'text',
                                    url:'<c:url value="/system/queryComboboxByDept.do"/>',
                                    required:false
                                }
                            }
                        },
                        {field:'orderId', title:'<span class="columnTitle">顺序</span>', width:60, sortable:true, editor:'text'},
                        {field:'createTime', title:'<span class="columnTitle">建立时间</span>', width:80, sortable:true},
                        {field:'deltag', title:'<span class="columnTitle">删除标志</span>', width:40, formatter:deltagFormatter,
                            editor:{
                                type:'checkbox',
                                options:{
                                    on:'1',
                                    off:'0'
                                }
                            }
                        },
                        {field:'opt', title:'<span class="columnTitle">操作</span>', width:30, align:'center', rowspan:2,
                            formatter:function (value, row, index) {
                                var optStr = '';
                                if (row.deltag == '0') {
                                    optStr += '<a href="#" style="color:red;text-decoration:none;" onclick="editFunction(\'' + row.roleId + '\',\'' + row.roleName + '\');">';
                                    optStr += '<img src="<c:url value="/images/admin/42.png" />" width="16" height="16" border="0" alt="授权">';
                                    optStr += '</a>';
                                } else {
                                    optStr += '<img src="<c:url value="/images/admin/42-1.png" />" style="" width="16" height="16" border="0" />';
                                }
                                return optStr;
                            }
                        }
                    ]
                ],
                toolbar:[
                    {
                        text:'添加',
                        iconCls:'icon-add',
                        handler: addRow
                    },
                    {
                        text:'删除',
                        iconCls:'icon-remove',
                        handler: deleteRow
                    },
                    {
                        text:'保存',
                        iconCls:'icon-save',
                        handler: saveRow
                    },
                    {
                        text:'取消',
                        iconCls:'icon-undo',
                        handler:function () {
                            $('#displayTable').datagrid('rejectChanges');
                        }
                    },
                    {
                        text:'GetChanges',
                        iconCls:'icon-search',
                        handler:function () {
                            var rows = $('#displayTable').datagrid('getChanges');
                            alert('changed rows: ' + rows.length + ' lines');
                        }
                    }
                ],
                onBeforeLoad:function () {
                    $(this).datagrid('rejectChanges');
                },
                onDblClickRow:function (rowIndex) {
                    if (lastIndex != rowIndex) {
                        $('#displayTable').datagrid('endEdit', lastIndex);
                        $('#displayTable').datagrid('beginEdit', rowIndex);
                        lastIndex = rowIndex;
                    }
                }
            });
            //设置分页控件
            var p = $('#displayTable').datagrid('getPager');
            $(p).pagination({
                pageSize:10, //每页显示的记录条数，默认为10
                pageList:[10, 20, 30, 40, 50], //可以设置每页记录条数的列表
                beforePageText:'第', //页数文本框前显示的汉字
                afterPageText:'页    共 {pages} 页',
                displayMsg:'当前显示 {from} - {to} 条记录   共 {total} 条记录'
            });
        }

        function getRowIndex(target){
            var tr = $(target).closest('tr.datagrid-row');
            return parseInt(tr.attr('datagrid-row-index'));
        }

        function endEditRow() {
            if (lastIndex != rowIndex) {
                $('#displayTable').datagrid('endEdit', lastIndex);
            }
        }

        function editrow(target){
            var rowIndex = getRowIndex(target);
            if (lastIndex != rowIndex) {
                $('#displayTable').datagrid('endEdit', lastIndex);
            }
            $('#displayTable').datagrid('beginEdit', rowIndex);
            lastIndex = rowIndex;
        }

        function saveRow() {

            if (lastIndex != undefined) {
                $('#displayTable').datagrid('endEdit', lastIndex);
            }

            var insertRows = $('#displayTable').datagrid('getChanges','inserted');
            var updateRows = $('#displayTable').datagrid('getChanges','updated');
            var deleteRows = $('#displayTable').datagrid('getChanges','deleted');
            // 改变过的记录集合
            var changesRows = {
                inserted : [],
                updated : [],
                deleted : []
            };

            if (insertRows.length>0) {
                for (var i=0;i<insertRows.length;i++) {
                    changesRows.inserted.push(insertRows[i]);
                }
            }

            if (updateRows.length>0) {
                for (var k=0;k<updateRows.length;k++) {
                    changesRows.updated.push(updateRows[k]);
                }
            }

            if (deleteRows.length>0) {
                for (var j=0;j<deleteRows.length;j++) {
                    changesRows.deleted.push(deleteRows[j]);
                }
            }

            //alert(JSON.stringify(changesRows));

            $.ajax({
                type: "post",
                url: "<c:url value='/system/saveRoles.do'/>",
                dataType:'json',
                data:{jsonStr: JSON.stringify(changesRows)},
                success: function (data) {
                    if (data.success) {
                        alert(data.message);
                    }
                }
            });
        }

        function deleteRow() {
            var rows = $('#displayTable').datagrid('getSelections');
            if (!rows || rows.length == 0) {
                alert('请选择需要删除的角色！');
                return;
            }

            confirm('是否确认删除选中的角色！', function(){
                while (rows && rows.length > 0) {
                    var index = $('#displayTable').datagrid('getRowIndex', rows[0]);
                    $('#displayTable').datagrid('deleteRow', index);
                }
            });
        }

        function addRow() {
            $('#displayTable').datagrid('endEdit', lastIndex);
            $('#displayTable').datagrid('appendRow', {
                roleName:'',
                deptId:'',
                orderId:'',
                deltag:'0'
            });
            lastIndex = $('#displayTable').datagrid('getRows').length - 1;
            $('#displayTable').datagrid('selectRow', lastIndex);
            $('#displayTable').datagrid('beginEdit', lastIndex);
        }

        function deptFormatter(value){
            for(var i=0; i<depts.length; i++){
                if (depts[i][0] == value) {
                    return depts[i][1];
                }
            }
            return value;
        }

        function deltagFormatter(value){
            return value == '1' ? '是' : '否';
        }

        $(function() {
            $("#tj").click(function() {


            });
        });

        function editFunction(id, name) {
            $('#showRoleId').html(id);
            $('#showRoleName').html(name);
            $('#fucntionRoleId').val(id);

            //提交的参数，name和inch是和struts action中对应的接收变量
            var params = {
                "function.roleId" : id
            };

            /*
            $.ajax({
                type: "POST",
                url: "<c:url value='/system/queryTreeFunction.do' />",
                data: params,
                dataType:"text", //ajax返回值设置为text（json格式也可用它返回，可打印出结果，也可设置成json）
                success: function(json){
                    //var obj = $.parseJSON(json);  //使用这个方法解析json
                    //var state_value = obj.result;  //result是和action中定义的result变量的get方法对应的
                    alert(json);
                },
                error: function(json){
                    alert("json=" + json);
                    return false;
                }
            });
            */

            $('#functionTree').tree({
                checkbox:true,
                url:'<c:url value="/system/queryAllTreeFunction.do?function.roleId=" />' + id
                /*,
                onBeforeExpand: function(node){
                    $('#functionTree').tree('options').url = '<c:url value="/system/queryTreeFunction.do?function.roleId=" />'
                            + id + '&function.funSuperior=' + node.id;
                }*/
            });

            $('#functionDialog').window('open');

        }

        function saveFunction() {
            var roelId = $('#fucntionRoleId').val();
            var nodes = $('#functionTree').tree('getChecked');

            var functions = '';
            var states = '';
            for(var i=0; i<nodes.length; i++){
                functions += nodes[i].id + ',';
                states += nodes[i].state + ',';
            }

            for(var i=0; i<nodes.length; i++){
                var pNode = $('#functionTree').tree('getParent',nodes[i].target);
                if (pNode.id != '-1' && !pNode.checked && functions.indexOf(pNode.id) < 0) {
                    functions += pNode.id + ',';
                    states += 'open,';
                }
            }

            //提交的参数，name和inch是和struts action中对应的接收变量
            var params = {
                "role.roleId" : roelId,
                "role.orderId" : states,
                "role.roleName" : functions
            };


            $.ajax({
                type: "POST",
                url: "<c:url value='/system/saveRoleFunctions.do' />",
                data: params,
                dataType:"json", //ajax返回值设置为text（json格式也可用它返回，可打印出结果，也可设置成json）
                success: function(data){
                    if (data.success) {
                        $.messager.alert('提示信息', data.message)
                    }
                },
                error: function(data){
                    $.messager.alert("json=" + data);
                    return false;
                }
            });

        }


    function cancelFunction(){
        $('#functionDialog').window('close');
    }


    </script>
</head>
<body>
<!-- 角色列表DIV -->
<table id="displayTable"></table>
<!-- 用户权限信息DIV -->
<div id="functionDialog" class="easyui-window"
     modal="true" minimizable="false" maximizable="false" collapsible="false" title="角色授权管理" closed="true"
     style="width:580px;height:480px;padding:5px;">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'center',border:false" style="padding:5px;background:#fff;border:1px solid #ccc;overflow-y:scroll;">
            <fieldset style="width: 520px; height: 30px; margin-bottom: 10px;">
                <div style="width:210px;float: left;padding: 8px; ">
                    角色ID：<label id="showRoleId"></label>
                    <input id="fucntionRoleId" type="hidden" value="roleId" />
                </div>
                <div style="width:210px;float: left;padding: 8px; ">
                    角色名称：<label id="showRoleName"></label>
                </div>
            </fieldset>
            <fieldset style="width: 520px;">
                <legend style="color: green;">权限</legend>
                <ul id="functionTree" class="easyui-tree"></ul>
            </fieldset>
        </div>
        <div data-options="region:'south',border:false" style="text-align:right;padding:5px 0;">
            <a href="#" class="easyui-linkbutton" iconCls="icon-ok" style="margin-right: 15px;" onclick="saveFunction();">确定</a>
            <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" style="margin-right: 15px;" onclick="cancelFunction();">取消</a>
        </div>
    </div>
</div>
</body>
</html>